package com.sunthy.mall.controller.admin;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.sunthy.mall.model.admin.bo.admin.AdminChangePwd;
import com.sunthy.mall.model.admin.pojo.admin.Admin;
import com.sunthy.mall.model.admin.Result;
import com.sunthy.mall.model.admin.bo.admin.AdminAddBo;
import com.sunthy.mall.model.admin.bo.admin.AdminLoginBo;
import com.sunthy.mall.model.admin.bo.admin.AdminSearchBo;
import com.sunthy.mall.model.admin.vo.admin.AllAdminVO;
import com.sunthy.mall.model.admin.vo.admin.LoginVo;
import com.sunthy.mall.service.admin.admin.AdminService;
import com.sunthy.mall.service.admin.admin.AdminServiceImpl;
import com.sunthy.mall.utils.HttpUtils;
import com.sunthy.mall.utils.RegularUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 用来处理后台管理系统的管理员模块的增删改查等操作
 */
@WebServlet("/api/admin/admin/*")
public class AdminServlet extends HttpServlet {

    private Gson gson = new Gson();

    private AdminService adminService = new AdminServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String replace = requestURI.replace(request.getContextPath() + "/api/admin/admin/", "");
        if ("login".equals(replace)) {

            // 登录
            login(request, response);

        } else if ("addAdminss".equals(replace)) {

            // 添加管理员用户
            addAdminss(request, response);

        } else if ("updateAdminss".equals(replace)) {

            // 修改管理员信息
            updateAdminss(request, response);

        } else if ("getSearchAdmins".equals(replace)) {

            // 搜索管理员信息
            getSearchAdmins(request, response);

        } else if ("changePwd".equals(replace)) {

            // 修改admin密码
            changePwd(request, response);

        }
    }

    /****************
     * 修改admin密码的逻辑:
     *  1.接收请求参数
     *  2.修改密码
     *  3.返回结果
     * @param request
     * @param response
     */
    private void changePwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String requestBody = HttpUtils.getRequestBody(request);
        AdminChangePwd adminChangePwd = gson.fromJson(requestBody, AdminChangePwd.class);
        // 校验参数
        String oldPwd = adminChangePwd.getOldPwd();
        String newPwd = adminChangePwd.getNewPwd();
        String confirmPwd = adminChangePwd.getConfirmPwd();
        // 判断是否为空字符串
        if ("".equals(oldPwd)) {
            response.getWriter().println(gson.toJson(Result.error("oldPwd不能为空")));
            return;
        }
        if ("".equals(newPwd)) {
            response.getWriter().println(gson.toJson(Result.error("newPwd不能为空")));
            return;
        }
        if ("".equals(confirmPwd)) {
            response.getWriter().println(gson.toJson(Result.error("confirmPwd不能为空")));
            return;
        }
        // 判断新旧密码是否相同
        if (oldPwd.equals(newPwd)) {
            response.getWriter().println(gson.toJson(Result.error("新密码不能和旧密码重复")));
            return;
        }
        // 正则校验
        // 密码最少8位,最多16位，至少1个大写字母，1个小写字母，1个数字 和 1个特殊字符
        StringBuffer pwd = RegularUtils.pwd(newPwd);
        if (pwd.length() != 0) {
            response.getWriter().println(gson.toJson(Result.error(pwd.toString())));
            return;
        }
        // 判断新密码和确认密码是否就相同
        if (!newPwd.equals(confirmPwd)) {
            response.getWriter().println(gson.toJson(Result.error("新密码和确认新密码必须一致")));
            return;
        }
        // 修改密码
        int code = adminService.updatePwd(adminChangePwd);
        // 返回请求
        if (code == 0) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("修改异常")));
    }

    /**
     * 搜索管理员信息的逻辑:
     * 1.接收提交过来的请求参数
     * 2.去数据库中查询
     * 3.返回结果给客户端
     *
     * @param request
     * @param response
     */
    private void getSearchAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String requestBody = HttpUtils.getRequestBody(request);
        // 将参数封装成 AdminSearchBo 对象
        AdminSearchBo adminSearchBo = gson.fromJson(requestBody, AdminSearchBo.class);

        List<AllAdminVO> searAllAdminVOS = adminService.searAllAdmins(adminSearchBo);
        response.getWriter().println(gson.toJson(Result.ok(searAllAdminVOS)));
    }

    /**
     * 修改数据方法的逻辑:
     *      1.首先接收提交过来的参数
     *      2.然后 将请求参数和数据库中数据惊醒比对  Email是否重复 进行修改
     *      3.返回一个结果给客户端
     *
     * @param request
     * @param response
     */
    private void updateAdminss(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String requestBody = HttpUtils.getRequestBody(request);
        // 将请求的json语句转换为AdminAddVo对象 adminAddVo
        AllAdminVO adminInfo = gson.fromJson(requestBody, AllAdminVO.class);

        // 调用service的update方法
        int code = adminService.update(adminInfo);
        if (code == 0) {// 成功
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }// 失败
        response.getWriter().println(gson.toJson(Result.error("该账号不允许重复使用")));
    }

    /**
     * 添加用户的逻辑:
     *      1.首先需要接收到用户提交过来的请求参数
     *      2.然后 把请求参数放置到数据库中进行比对,判断email是否重复  ,进行添加
     *      3.返回一个结果给客户端
     *
     * @param request
     * @param response
     */
    private void addAdminss(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String requestBody = HttpUtils.getRequestBody(request);
        // 将请求的json语句转换为AdminAddBo对象 adminAddBo
        AdminAddBo adminAddBo = gson.fromJson(requestBody, AdminAddBo.class);

        // 调用service的add方法，返回结果即可
        int code = adminService.add(adminAddBo);
        if (code == 10000) {
            // 注册失败
            response.getWriter().println(Result.error("该账号不允许重复使用"));
            return;
        }
        // 注册成功
        response.getWriter().println(gson.toJson(Result.ok()));
    }


    /**
     * 登录的逻辑：
     *      1.首先需要接收到用户提交过来的请求参数
     *      2.将请求参数放置到数据库中进行比对，判断用户名，密码是否正确
     *      3.返回一个结果给客户端
     *
     * @param request
     * @param response
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String requestBody = HttpUtils.getRequestBody(request);
        // 将请求的json语句转换为AdminLoginBo对象 loginbo
        AdminLoginBo loginBo = gson.fromJson(requestBody, AdminLoginBo.class);
        // 校验
        // 首先判断 loginBo的Email,pwd是否为空
        if (StringUtils.isEmpty(loginBo.getEmail()) || StringUtils.isEmpty(loginBo.getPwd())) {
            response.getWriter().println(gson.toJson(Result.error("参数不能为空")));
            return;
        }
        // 去数据库中查找账号密码是否匹配
        int code = adminService.login(loginBo);
        if (code == 200) {// 登录成功
            //登录成功
            //往session里面写入一些数据
            HttpSession session = request.getSession();
            session.setAttribute("email", loginBo.getEmail());
            // 返回结果
            LoginVo loginVo = new LoginVo(loginBo.getEmail(), loginBo.getEmail());
            response.getWriter().println(gson.toJson(Result.ok(loginVo)));
            return;
        }// 登录失败
        response.getWriter().println(gson.toJson(Result.error("登陆失败!账号,密码错误")));
    }



    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String replace = requestURI.replace(request.getContextPath() + "/api/admin/admin/", "");
        if ("allAdmins".equals(replace)) {

            // 显示所有后台管理员
            allAdmins(request, response);

        }
        if ("getAdminsInfo".equals(replace)) {

            // 回显管理员信息
            getAdminInfo(request, response);

        }
        if ("deleteAdmins".equals(replace)) {

            // 删除管理员
            deleteAdmins(request, response);

        }
    }

    /**
     * 删除管理员的逻辑:
     *      1.接收请求参数
     *      2.删除数据库中对应id的数据
     *      3.返回Result类型结果给客户端
     *
     * @param request
     * @param response
     */
    private void deleteAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String idStr = request.getParameter("id");
        int id = Integer.parseInt(idStr);
        int code = adminService.delete(id);
        if (code == 0) {// 成功
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        } // 失败
        response.getWriter().println(gson.toJson(Result.error("删除异常")));
    }

    /**
     * 回显的逻辑:
     *      1.接收请求参数id=..
     *      2.将id放置到数据库中比对,查找admin
     *      3.返回结果给客户端
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void getAdminInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String idStr = request.getParameter("id");
        int id = Integer.parseInt(idStr);

        Admin adminInfo = adminService.getAdminInfo(id);
        AllAdminVO allAdminVO = new AllAdminVO(adminInfo.getId(), adminInfo.getUsername(), adminInfo.getPassword(), adminInfo.getNickname());
        response.getWriter().println(gson.toJson(Result.ok(allAdminVO)));
    }

    /**
     * 显示所有后台管理员的方法
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void allAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<AllAdminVO> adminVOS = adminService.allAdmins();
        response.getWriter().println(gson.toJson(Result.ok(adminVOS)));
    }

}
